package cn.cas.mango.util.string;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

public class StringUtils {
  public static String preprocessString(String prepareString) {
    return prepareString.replaceAll("“", "\"")
        .replaceAll("”", "\"")
        .replaceAll("（", "(")
        .replaceAll("）", ")");
  }

  public static int countChar(String str, char ch) {
    return (int) str.chars().filter(c -> c == ch).count();
  }

  public static String strip(String str) {
    if (str == null) {
      return null;
    }
    // 使用正则表达式去除Unicode空白字符
    return str.replaceAll("^\\p{Zs}+|\\p{Zs}+$", "");
  }

  public static boolean containsAny(String source, String target) {
    if (source == null || target == null) {
      return false;
    }

    return target.chars().anyMatch(c -> source.indexOf(c) >= 0);
  }

  public static String getUUID() {
    SecureRandom secureRandom = new SecureRandom();
    byte[] seed = secureRandom.generateSeed(16);
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
    md5.update(seed);
    UUID uuid = UUID.nameUUIDFromBytes(md5.digest());
    String ret = uuid.toString();
    return ret.substring(0, Math.min(ret.length(), 8));
  }
}
